package com.emit.security.resultReturned;

import com.alibaba.fastjson.JSON;
import com.emit.security.ResultCode;
import com.emit.utils.Constant;
import com.emit.view.ResultView;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author zhengshuai
 * @date 2021/5/25
 * @Description: 登录成功处理逻辑
 */
@Component
public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException, IOException {
        User userDetails = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //业务操作

        //返回json数据
        ResultView resultView=new ResultView();
        resultView.setMsg(ResultCode.SUCCESS.getMessage());
        resultView.setCode(String.valueOf(ResultCode.SUCCESS.getCode()));
        resultView.setData(userDetails);
        //处理编码方式，防止中文乱码的情况
        httpServletResponse.setContentType(Constant.CONTENT_TYPE);
        //塞到HttpServletResponse中返回给前台
        httpServletResponse.getWriter().write(JSON.toJSONString(resultView));
    }
}
